//
//  PickImageViewController.m
//  ShareNavigation
//
//  Created by 水木 傅 on 12-5-10.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "PickImageViewController.h"
#import "SignInViewController.h"
#import "SingletonUser.h"
#import "ASIFormDataRequest.h"
#import <QuartzCore/QuartzCore.h>
#import "MainViewController.h"

@implementation PickImageViewController
@synthesize pickImage;
@synthesize sendFeelText;
@synthesize imageName;
@synthesize feelText;
@synthesize currentUserLocation;
@synthesize hasImage;
@synthesize addressLabel;
@synthesize bmkSearch;

-(void)viewDidLoad
{
    [super viewDidLoad];
    //---  设置选择图片的名称  ---
    imageName = [self stringWithUUID];
    feelText = @"";
    NSLog(@"%f   ...  %f",currentUserLocation.coordinate.latitude,currentUserLocation.coordinate.longitude);
    //---  通过经纬度进行地址的反编辑  ---
    bmkSearch = [[BMKSearch alloc] init];
    bmkSearch.delegate = self;
    //---  反编译地址要用的经纬度  ---
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D)
                                {currentUserLocation.coordinate.latitude, currentUserLocation.coordinate.longitude};
    [bmkSearch reverseGeocode:pt];    
    //---  输入框设置圆角  ---
    [self.sendFeelText.layer setBorderColor:[[UIColor grayColor] CGColor]];
    [self.sendFeelText.layer setBorderWidth:1.0];
    [self.sendFeelText.layer setCornerRadius:8.0];
    [self.sendFeelText.layer setMasksToBounds:YES];
    self.sendFeelText.clipsToBounds = YES;
    self.sendFeelText.delegate = self;
}

- (void)viewDidUnload {
    [self setPickImage:nil];
    [self setSendFeelText:nil];
    [self setAddressLabel:nil];
    [super viewDidUnload];
}
//生成随即的uuid
- (NSString*) stringWithUUID {
    CFUUIDRef    uuidObj = CFUUIDCreate(nil);//create a new UUID
    //get the string representation of the UUID
    NSString    *uuidString =(__bridge_transfer NSString *)CFUUIDCreateString(nil, uuidObj);
    CFRelease(uuidObj);
    return uuidString;
}

//---  界面按钮的响应函数  ---
//---  图片库获取图片  ---
- (IBAction)pickImageFromLibrary:(id)sender {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) 
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentModalViewController:picker animated:YES];
    }
    else 
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"访问图片库出错" message:@"设备不支持图片库访问" delegate:nil cancelButtonTitle:@"返回!" otherButtonTitles:nil];
        [alert show];
    }
}

//---  摄像头获取图片  ---
- (IBAction)pickImageFromCamera:(id)sender {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentModalViewController:picker animated:YES];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"使用摄像头出错" message:@"设备不支持拍照访问" delegate:nil cancelButtonTitle:@"返回!" otherButtonTitles:nil];
        [alert show];
    }
}

//---  确定签到  ---
-(void) requestSignInFinished:(ASIHTTPRequest *)request
{
    NSString *ResponseString = [request responseString];
    NSLog(@"%@",ResponseString);
    if([ResponseString isEqualToString:@"TRUE"])
    {
        UIAlertView *alert;
        alert = [[UIAlertView alloc]
                 initWithTitle:@""
                 message:@"签到成功"
                 delegate:self
                 cancelButtonTitle:@"返回"
                 otherButtonTitles:nil];
        alert.tag = 0;
        [alert show];
    }
    else
    {
        UIAlertView *alert;
        alert = [[UIAlertView alloc]
                 initWithTitle:@"错误"
                 message:ResponseString
                 delegate:self
                 cancelButtonTitle:@"返回"
                 otherButtonTitles:@"重新发送签到信息",nil];
        [alert show];
    }
}
-(void) requestSignInFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",[error localizedFailureReason]);
    UIAlertView *alert;
    alert = [[UIAlertView alloc]
             initWithTitle:@""
             message:[[request error] localizedFailureReason]
             delegate:self
             cancelButtonTitle:@"返回"
             otherButtonTitles:@"重新发送签到信息",nil];
    [alert show];
}

-(void) sendSignIn
{
    
    feelText = sendFeelText.text;
    NSURL *url = [NSURL URLWithString:@"http://localhost/~walker/ShareNavigationSVN/trunk/ShareNavigationPHP/SignIn.php"];
    ASIFormDataRequest *request=[[ASIFormDataRequest alloc] initWithURL:url];
    [request setRequestMethod:@"POST"];
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(requestSignInFinished:)];
    [request setDidFailSelector:@selector(requestSignInFailed:)];
    [request setDefaultResponseEncoding:NSUTF8StringEncoding];
    //[request setPostValue:<#(id<NSObject>)#> forKey:<#(NSString *)#>];
    NSString *latitude = [NSString stringWithFormat:@"%f",
                          currentUserLocation.location.coordinate.latitude ];
    NSString *longitude = [NSString stringWithFormat:@"%f",
                           currentUserLocation.location.coordinate.longitude ];
    NSString *user = [[SingletonUser shareManager] UserID];
    //---  发送数据  ---
    [request setPostValue:imageName forKey:@"UUID"];
    [request setPostValue:user forKey:@"UserId"];
    [request setPostValue:feelText forKey:@"Signature"];
    [request setPostValue:latitude forKey:@"Latitude"];
    [request setPostValue:longitude forKey:@"Longitude"];
    [request setPostValue:addressLabel.text forKey:@"Address"];
    //---  如果有选中图片  ---
    if(hasImage == TRUE)
    {
        [request setPostValue:@"TRUE" forKey:@"HasImage"];
        //---  获取图片数据  ---
        NSData *imageData = UIImagePNGRepresentation(pickImage.image);
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        //---  设置图片在本应用程序中的位置  ---
        NSString *archivePath = [documentsDirectory 
                                 stringByAppendingPathComponent:
                                 [NSString stringWithFormat:@"%@.jpg",imageName]];
        [request addData:imageData withFileName:archivePath andContentType:@"image/jpg" 
                  forKey:@"image"];
    }
    else
    {
        [request setPostValue:@"FALSE" forKey:@"HasImage"];
    }
    //---  发送请求信息  ----
    [request startAsynchronous];
}
//---  发送请求  ---
- (IBAction)signInButton:(id)sender 
{       
    [self sendSignIn];
}

#pragma 图片选择的委托
//---  从图片库中选择图片  ---
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    NSData *imageData = UIImagePNGRepresentation(image);
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    //---  设置图片在本应用程序中的位置  ---
    NSString *archivePath = [documentsDirectory 
                             stringByAppendingPathComponent:
                             [NSString stringWithFormat:@"%@.jpg",imageName]];
    [imageData writeToFile:archivePath  atomically:YES];
    pickImage.image = image;
    self.hasImage = TRUE;
    [self dismissModalViewControllerAnimated:YES];
}
//---  从相机获取图片  ---
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
    NSData *imageData = UIImagePNGRepresentation(image);
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *archivePath = [documentsDirectory 
                             stringByAppendingPathComponent:
                             [NSString stringWithFormat:@"%@.jpg",imageName]];
    [imageData writeToFile:archivePath  atomically:YES];
    pickImage.image = image;
    self.hasImage = TRUE;
    [self dismissModalViewControllerAnimated:YES];
}


#pragma  实现一些textview委托事件
//---  准备开始编辑文字  ---
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    if(![textView.textColor isEqual:[UIColor blackColor]])
    {
        NSLog(@"textViewShouldBeginEditing");
        textView.text = @"";
        textView.textColor = [UIColor blackColor];
    }
    return YES;
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([@"\n" isEqualToString:text] == YES) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

-(BOOL)textViewShouldEndEditing:(UITextView *)textView
{
   /* NSLog(@"textViewShouldEndEditing");*/
    [textView resignFirstResponder];
    return YES;
}

-(void)textViewDidChange:(UITextView *)textView
{
    if([textView.text length] > 130)
    {
        NSRange rang;
        rang.location = 0;
        rang.length = 140;
        textView.text = [textView.text substringWithRange:rang];
    }
    NSLog(@"%d",textView.text.length);
}

-(void)textViewDidEndEditing:(UITextView *)textView
{
    self.feelText = textView.text;
    [textView resignFirstResponder];
}

#pragma ---  使用百度图通过经纬度进行地址显示  ---
-(void)onGetAddrResult:(BMKAddrInfo *)result errorCode:(int)error
{
    if([result.strAddr length] == 0)
    {
        float flongitude = currentUserLocation.coordinate.longitude;
        float flatitude = currentUserLocation.coordinate.latitude;
        NSString *longitude;
        NSString *latitude;
        if(flongitude > 0)
        {
            longitude = [NSString stringWithFormat:@"东经：%.2f",flongitude];
        }
        else
        {
            
            longitude = [NSString stringWithFormat:@"西经：%.2f",-flongitude];
        }
        if(flatitude > 0)
        {
            latitude = [NSString stringWithFormat:@"北纬：%.2f",flatitude];
        }
        else
        {
            latitude = [NSString stringWithFormat:@"南纬：%.2f",-flatitude];
        }
        addressLabel.text = [NSString stringWithFormat:@"%@, %@",longitude,latitude];
    }
    else
    {
        NSLog(@"-----%@-----",result.strAddr);
        addressLabel.text = result.strAddr;
    }
}

#pragma ---  实现delegate中的方法  ----

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag == 0)
    {
        [[self navigationController]popViewControllerAnimated:YES];
    }
    else
    {
        if(buttonIndex == 0)
        {
            //自动关闭弹出框
        }
        else if(buttonIndex == 1)
        {
            [self sendSignIn];
        }
    }
}

@end





